package org.jeecg.modules.online.cgform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.auth.service.IOnlAuthPageService;
import org.jeecg.modules.online.cgform.components.LinkDown;
import org.jeecg.modules.online.cgform.constant.ExtendJsonKey;
import org.jeecg.modules.online.cgform.entity.OnlCgformButton;
import org.jeecg.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.enums.CgformConstant;
import org.jeecg.modules.online.cgform.model.*;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.service.IOnlineService;
import org.jeecg.modules.online.cgform.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("onlineService")
@Slf4j
public class OnlineServiceImpl implements IOnlineService {

    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;

    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IOnlAuthPageService onlAuthPageService;


    @Override
    //@Cacheable(value = CacheConstant.ONLINE_LIST, key = "#head.id+'-'+#username")
    public OnlComplexModel queryOnlineConfig(OnlCgformHead head, String username) {
        String headId = head.getId();
        // 获取参数 是否联合查询
        boolean isJoinQuery = CgformUtil.enableJoinQuery(head);
        //1.查询字段集合
        List<OnlCgformField> fieldList = getListColumns(headId);
        //update-begin-author:taoyan date:20200723 for:online权限改造
        //2.查询列表上需要被隐藏的列和按钮
        //List<String> hideColumns = onlCgformFieldService.selectOnlineHideColumns(head.getTableName());
        List<String> hideColumns = onlAuthPageService.queryHideCode(headId, true);
        //update-end-author:taoyan date:20200723 for:online权限改造
        //3.定义列
        List<OnlColumn> columns = new ArrayList<OnlColumn>();
        //4.定义字典配置
        Map<String, List<DictModel>> dictOptions = new HashMap<String, List<DictModel>>();
        // 定义 href插槽集合
        List<HrefSlots> fieldHrefSlots = new ArrayList<HrefSlots>();
        // 定义外键配置
        List<OnlForeignKey> foreignKeys = new ArrayList<OnlForeignKey>();
        List<String> excludeList = new ArrayList<String>();
        // 定义一个map 用于记录字段名 重名字段需要取别名
        Map<String,Integer> fieldRecord = new HashMap<>();
        //5.遍历
        for (OnlCgformField item : fieldList) {
            String dbFieldName = item.getDbFieldName();

            //如果当前列是外键
            String mainTable = item.getMainTable();
            String mainField = item.getMainField();
            if(StringUtil.isNotEmpty(mainField) && StringUtil.isNotEmpty(mainTable)){
                OnlForeignKey foreignKey = new OnlForeignKey(dbFieldName,mainField);
                foreignKeys.add(foreignKey);
            }

            //排除不显示的列
            if(item.getIsShowList()==null || CgformUtil.SHOW_LIST_YES!=item.getIsShowList()){
                continue;
            }

            //id 不显示
            if(CgformUtil.COLUMN_ID.equals(dbFieldName)) {
                continue;
            }
            // 如果隐藏的列
            if(hideColumns.contains(dbFieldName)) {
                continue;
            }

            if(excludeList.contains(dbFieldName)){
                continue;
            }

            OnlColumn column = getOnlColumnByField(item, dictOptions, fieldHrefSlots);
            fieldRecord.put(item.getDbFieldName(), 1);
            columns.add(column);
            // 联动组件 -联动层级往后的字段
            String linkField = column.getLinkField();
            if(linkField!=null && !"".equals(linkField)){
                initOtherLinkFields(fieldList,excludeList,columns,dbFieldName,linkField);
            }
        }
        // update-begin--Author:taoyan-Date:20210709-for: 联合查询新逻辑---
        if(isJoinQuery){
            // 获取子表所有的字段
            List<OnlColumn> subColumns = handleSubTableColumns(head, dictOptions, fieldHrefSlots, fieldRecord);
            if(subColumns.size()>0){
                //获取重复的列名
                List<String> duplicateFields = new ArrayList<>();
                for(String fieldName: fieldRecord.keySet()){
                    if(fieldRecord.get(fieldName)>1){
                        duplicateFields.add(fieldName);
                    }
                }
                for(OnlColumn column: subColumns){
                    String fieldName = column.getDataIndex();
                    if(duplicateFields.contains(fieldName)){
                        // 列表dataIndex 重复的列才需要加
                        column.setDataIndex(column.getTableName()+"_"+fieldName);
                    }
                    columns.add(column);
                }
            }
        }
        // update-end--Author:taoyan-Date:20210709-for: 联合查询新逻辑---

        OnlComplexModel model = new OnlComplexModel();
        model.setCode(headId);
        model.setTableType(head.getTableType());
        model.setFormTemplate(head.getFormTemplate());//表单风格
        model.setDescription(head.getTableTxt());//表描述
        model.setCurrentTableName(head.getTableName());//表名
        model.setPaginationFlag(head.getIsPage());//是否分页
        model.setCheckboxFlag(head.getIsCheckbox());//是否checkBox
        model.setScrollFlag(head.getScroll());//是否滚动条
        model.setRelationType(head.getRelationType());//主子关联关系

        model.setColumns(columns);
        model.setDictOptions(dictOptions);

        //href插槽
        model.setFieldHrefSlots(fieldHrefSlots);

        //外键
        model.setForeignKeys(foreignKeys);

        //隐藏的列
        model.setHideColumns(hideColumns);

        //自定义button
        List<OnlCgformButton> cgButtonList = this.onlCgformHeadService.queryButtonList(headId,true);
        List<OnlCgformButton> cgFinalBtnList = new ArrayList<OnlCgformButton>();
        for (OnlCgformButton onlCgformButton : cgButtonList) {
            if(hideColumns.contains(onlCgformButton.getButtonCode())) {
                continue;
            }
            cgFinalBtnList.add(onlCgformButton);
        }
        model.setCgButtonList(cgFinalBtnList);

        //JS增强
        OnlCgformEnhanceJs enhanceJs = this.onlCgformHeadService.queryEnhanceJs(headId, CgformUtil.ENHANCE_LIST);
        if(enhanceJs!=null && StringUtil.isNotEmpty(enhanceJs.getCgJs())) {
            String enhanceJsStr = EnhanceJsUtil.overFinalWriteJs(enhanceJs.getCgJs(), cgButtonList);
            model.setEnhanceJs(enhanceJsStr);
        }

        //是否树
        if("Y".equals(head.getIsTree())) {
            model.setPidField(head.getTreeParentIdField());
            model.setHasChildrenField(head.getTreeIdField());
            model.setTextField(head.getTreeFieldname());
        }

        return model;
    }

    /**
     * 获取 存储、展示的字段名 返回一个数组 第一个元素：存储字段 第二个元素：展示字段
     * @return
     */
    private String[] getStoreAndTextField(String str){
        String[] arr = new String[]{"", ""};
        if(str!=null && !"".equals(str)){
            JSONObject json = JSON.parseObject(str);
            if(json.containsKey(ExtendJsonKey.STORE)){
                arr[0] = oConvertUtils.camelToUnderline(json.getString(ExtendJsonKey.STORE));
            }
            if(json.containsKey(ExtendJsonKey.TEXT)){
                arr[1] = oConvertUtils.camelToUnderline(json.getString(ExtendJsonKey.TEXT));
            }
        }
        return arr;
    }

    private void initOtherLinkFields(List<OnlCgformField> fieldList,List<String> excludeList,List<OnlColumn> columns,String customRender,String linkField){
        if(StringUtil.isNotEmpty(linkField)){
            String[] arr = linkField.split(",");
            for(String key:arr){
                for(OnlCgformField item:fieldList){
                    String dbFieldName = item.getDbFieldName();
                    //排除不显示的列
                    if(CgformUtil.SHOW_LIST_YES!=item.getIsShowList()){
                        continue;
                    }
                    if(key.equals(dbFieldName)){
                        excludeList.add(key);
                        OnlColumn column = new OnlColumn(item.getDbFieldTxt(),dbFieldName);
                        column.setCustomRender(customRender);
                        columns.add(column);
                        break;
                    }
                }
            }

        }
    }

    @Override
    public JSONObject queryOnlineFormObj(OnlCgformHead head, OnlCgformEnhanceJs onlCgformEnhanceJs) {
        //定义对象
        JSONObject obj = new JSONObject();
        String headId = head.getId();
        String taskId = head.getTaskId();
        //查询有效字段
        List<OnlCgformField> fieldList = this.onlCgformFieldService.queryAvailableFields(headId, head.getTableName(), taskId, false);
        //查询被禁用字段
        //update-begin-author:taoyan date:20210326 for:online权限改造 支持工作流表单
        List<String> disabledFieldNameList = new ArrayList<String>();
        if(oConvertUtils.isEmpty(taskId)){
            //查询表【online】被禁用字段
            List<String> disabledOnlineList = this.onlAuthPageService.queryFormDisabledCode(head.getId());
            if(disabledOnlineList!=null && disabledOnlineList.size()>0 && disabledOnlineList.get(0)!=null){
                disabledFieldNameList.addAll(disabledOnlineList);
            }
        }else{
            //查询表【流程】被禁用字段
            List<String> disabledFlowList = this.onlCgformFieldService.queryDisabledFields(head.getTableName(), taskId);
            if(disabledFlowList!=null && disabledFlowList.size()>0 && disabledFlowList.get(0)!=null){
                disabledFieldNameList.addAll(disabledFlowList);
            }
        }
        //update-end-author:taoyan date:20210326 for:online权限改造 支持工作流表单
        //处理JS增强
        EnhanceJsUtil.overwriteJsOneOrMain(onlCgformEnhanceJs, head.getTableName(), fieldList);
        //获取树形配置信息
        TreeSelectColumn treeColumn = null;
        if("Y".equals(head.getIsTree())) {
            treeColumn = new TreeSelectColumn();
            treeColumn.setCodeField("id");
            treeColumn.setFieldName(head.getTreeParentIdField());
            treeColumn.setPidField(head.getTreeParentIdField());
            treeColumn.setPidValue("0");
            treeColumn.setHsaChildField(head.getTreeIdField());
            treeColumn.setTableName(CgformUtil.getRealTableName(head.getTableName()));
            treeColumn.setTextField(head.getTreeFieldname());
        }
        //组装schema
        JSONObject schema = CgformUtil.getJsonSchemaByCgformFieldList(fieldList,disabledFieldNameList,treeColumn);
        schema.put("table",head.getTableName());
        schema.put("describe",head.getTableTxt());
        //log.info("----动态表单获取JSON-SCHEMA>>"+schema.toJSONString());
        obj.put("schema", schema);
        //log.info("----动态表单获取JSON-SCHEMA>>"+schema.toJSONString());
        obj.put("head", head);

        //自定义button
        List<OnlCgformButton> cgButtonList = this.queryFormValidButton(headId);
        if(cgButtonList!=null && cgButtonList.size()>0) {
            obj.put("cgButtonList",cgButtonList);
        }
        //JS增强
        if(onlCgformEnhanceJs!=null && StringUtil.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            String tempString = EnhanceJsUtil.overwriteClearButton(onlCgformEnhanceJs.getCgJs(), cgButtonList);
            onlCgformEnhanceJs.setCgJs(tempString);
            obj.put("enhanceJs", EnhanceJsUtil.theLastString(onlCgformEnhanceJs.getCgJs()));
        }
        return obj;
    }

    @Override
    @Cacheable(value = CacheConstant.ONLINE_FORM, key = "'erp'+ #head.id+'-'+#username")
    public JSONObject queryOnlineFormObj(OnlCgformHead head, String username) {
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(head.getId(), CgformUtil.ENHANCE_FORM);
        return queryOnlineFormObj(head,onlCgformEnhanceJs);
    }

    @Override
    public List<OnlCgformButton> queryFormValidButton(String headId) {
        List<OnlCgformButton> cgButtonList = this.onlCgformHeadService.queryButtonList(headId, false);
        List<OnlCgformButton> ls = null;
        if(cgButtonList!=null && cgButtonList.size()>0) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = sysUser.getId();
            List<String> hide = this.onlAuthPageService.queryFormHideButton(userId, headId);
            ls = cgButtonList.stream()
                    .filter((OnlCgformButton button) -> (hide==null || hide.indexOf(button.getButtonCode())<0))
                    .collect(Collectors.toList());
        }
        return ls;
    }

    @Override
    @Cacheable(value = CacheConstant.ONLINE_FORM, key = "#head.id+'-'+#username")
    public JSONObject queryOnlineFormItem(OnlCgformHead head, String username) {
        head.setTaskId(null);
        return queryFormItemJson(head);
    }



    //author:scott--date:20220118--for:JTC-760 节点权限，配置了一个隐藏的控件，测试生效，然后把他删掉还是生效
    //@Cacheable(value = CacheConstant.ONLINE_FORM, key = "'flow' + #head.id + '-' + #username + '-' + #taskId")
    @Override
    public JSONObject queryFlowOnlineFormItem(OnlCgformHead head, String username, String taskId) {
        head.setTaskId(taskId);
        return queryFormItemJson(head);
    }

    @Override
    @Cacheable(value = CacheConstant.ONLINE_FORM, key = "'enhancejs' + #code + '-' + #type")
    public String queryEnahcneJsString(String code, String type) {
        String enhanceJsStr = "";
        OnlCgformEnhanceJs enhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, type);
        if(enhanceJs!=null && StringUtil.isNotEmpty(enhanceJs.getCgJs())) {
            //update-begin-author:taoyan date:20200212 for:TASK #3235 【严重】Online表单JS增强使用了ES6语法，IE不兼容
            enhanceJsStr = EnhanceJsUtil.overFinalWriteJs(enhanceJs.getCgJs(), null);
            //update-end-author:taoyan date:20200212 for:TASK #3235 【严重】Online表单JS增强使用了ES6语法，IE不兼容
        }
        return enhanceJsStr;
    }

    /**
     * 根据表id查询列表显示的列且按OrderNum正序排序
     * @param headId
     * @return
     */
    private List<OnlCgformField> getListColumns(String headId){
        LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
        query.eq(OnlCgformField::getCgformHeadId, headId);
        //query.eq(OnlCgformField::getIsShowList, CgformUtil.SHOW_LIST_YES);
        query.orderByAsc(OnlCgformField::getOrderNum);
        return onlCgformFieldService.list(query);
    }

    /**
     * 查询 表单配置json
     * head.taskId如果存在 视为流程表单
     * @param head
     * @return
     */
    private JSONObject queryFormItemJson(OnlCgformHead head){
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(head.getId(), CgformUtil.ENHANCE_FORM);
        JSONObject obj = this.queryOnlineFormObj(head,onlCgformEnhanceJs);
        obj.put("formTemplate",head.getFormTemplate());
        //log.info("----动态表单获取JSON-SCHEMA>>"+schema.toJSONString());
        if(head.getTableType()==2) {
            //主表 则需要写一下schema
            JSONObject schema = obj.getJSONObject("schema");
            String subStr = head.getSubTableStr();
            if(StringUtil.isNotEmpty(subStr)) {
                List<OnlCgformHead> subHeadList = new ArrayList<OnlCgformHead>();
                for (String tbname : subStr.split(",")) {
                    OnlCgformHead tempTable = this.onlCgformHeadService.getOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, tbname));
                    if(tempTable==null) {
                        continue;
                    }
                    subHeadList.add(tempTable);
                }
                if(subHeadList.size()>0){
                    //排序逻辑
                    Collections.sort(subHeadList, new Comparator<OnlCgformHead>() {
                        @Override
                        public int compare(OnlCgformHead o1, OnlCgformHead o2) {
                            Integer o1OrderNum = o1.getTabOrderNum();
                            if (o1OrderNum == null) {
                                o1OrderNum = 0;
                            }
                            Integer o2OrderNum = o2.getTabOrderNum();
                            if (o2OrderNum == null) {
                                o2OrderNum = 0;
                            }
                            return o1OrderNum.compareTo(o2OrderNum);
                        }
                    });

                    for (OnlCgformHead tempTable : subHeadList) {
                        //查询子表字段
                        List<OnlCgformField> subFieldList = this.onlCgformFieldService.queryAvailableFields(tempTable.getId(), tempTable.getTableName(), head.getTaskId(), false);
                        //处理JS增强
                        //update-begin-author:taoyan date:20200212 for:TASK #3235 【严重】Online表单JS增强使用了ES6语法，IE不兼容
                        EnhanceJsUtil.overwriteJsSub(onlCgformEnhanceJs, tempTable.getTableName(), subFieldList);
                        //update-end-author:taoyan date:20200212 for:TASK #3235 【严重】Online表单JS增强使用了ES6语法，IE不兼容
                        JSONObject subJson = new JSONObject();
                        //查询被禁用字段
                        //update-begin-author:taoyan date:20200723 for:online权限改造
                        List<String> subDisabledFieldNameList = new ArrayList<String>();
                        if(StringUtil.isNotEmpty(head.getTaskId())){
                            //查询【流程】中被禁用字段
                            subDisabledFieldNameList = this.onlCgformFieldService.queryDisabledFields(tempTable.getTableName(),head.getTaskId());
                        }else{
                            //查询【online】中被禁用字段
                            subDisabledFieldNameList = this.onlAuthPageService.queryFormDisabledCode(tempTable.getId());
                        }
                        //update-end-author:taoyan date:20200723 for:online权限改造

                        if(1==tempTable.getRelationType()) {
                            //one to one
                            subJson = CgformUtil.getJsonSchemaByCgformFieldList(subFieldList,subDisabledFieldNameList,null);
                        }else {
                            //one to many
                            subJson.put("columns",  CgformUtil.getJEditableTableColumnsJson(subFieldList,subDisabledFieldNameList));
                            //设置隐藏的按钮 表单页面 子表一对多用到【子表行编辑组件】
                            List<String> subHideButtons = onlAuthPageService.queryListHideButton(null, tempTable.getId());
                            subJson.put("hideButtons", subHideButtons);
                        }
                        //设置外键字段（对应的主表字段）
                        String foreignKey = this.onlCgformFieldService.queryForeignKey(tempTable.getId(), head.getTableName());
                        subJson.put("foreignKey", foreignKey);

                        subJson.put("id", tempTable.getId());
                        //subJson.put("columns",  CgformUtil.getJEditableTableColumnsJson(subFieldList));
                        subJson.put("describe", tempTable.getTableTxt());
                        subJson.put("key", tempTable.getTableName());
                        subJson.put("view", "tab");
                        subJson.put("order",tempTable.getTabOrderNum());//增加排序字段标识子表顺序
                        subJson.put("relationType", tempTable.getRelationType());
                        subJson.put("formTemplate", tempTable.getFormTemplate());
                        schema.getJSONObject("properties").put(tempTable.getTableName(), subJson);
                    }
                }
            }
            //JS增强
            if(onlCgformEnhanceJs!=null && StringUtil.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
                obj.put("enhanceJs", EnhanceJsUtil.theLastString(onlCgformEnhanceJs.getCgJs()));
            }
        }
        return obj;
    }

    /**
     * 根据字段配置 获取列信息
     * @param item
     * @param dictOptions
     * @param fieldHrefSlots
     * @return
     */
    private OnlColumn getOnlColumnByField(OnlCgformField item, Map<String, List<DictModel>> dictOptions, List<HrefSlots> fieldHrefSlots){
        String dbFieldName = item.getDbFieldName();

        OnlColumn column = new OnlColumn(item.getDbFieldTxt(),dbFieldName);
        String dictCode = item.getDictField();
        String view = item.getFieldShowType();
        //TODO A.抽象以下逻辑 按对象处理是否好点 B.那个字典数据的加载是否应该放在前端
        if(StringUtil.isNotEmpty(dictCode) && !"popup".equals(view)) {
            List<DictModel> ls = new ArrayList<DictModel>();
            //普通字典 + 表字典
            if(StringUtil.isNotEmpty(item.getDictTable())) {
                ls = sysBaseAPI.queryTableDictItemsByCode(item.getDictTable(), item.getDictText(), dictCode);
            }else if(StringUtil.isNotEmpty(item.getDictField())) {
                ls = sysBaseAPI.queryDictItemsByCode(dictCode);
            }
            dictOptions.put(dbFieldName,ls);
            column.setCustomRender(dbFieldName);
        }

        if(CgformUtil.SWITCH.equals(view)){
            List<DictModel> ls = CgformUtil.getSwitchComponentDict(item);
            dictOptions.put(dbFieldName,ls);
            column.setCustomRender(dbFieldName);
        }

        if(CgformUtil.LINK_DOWN.equals(view)){
            String jsonStr = item.getDictTable();
            LinkDown json = JSONObject.parseObject(jsonStr, LinkDown.class);
            try {
                List<DictModel> ls = sysBaseAPI.queryTableDictItemsByCode(json.getTable(), json.getTxt(), json.getKey());
                dictOptions.put(dbFieldName,ls);
                column.setCustomRender(dbFieldName);
                column.setLinkField(json.getLinkField());
            }catch (Exception e){
                log.warn("联动组件配置错误!",e.getMessage());
            }
        }

        if(CgformUtil.SEL_TREE.equals(view)) {
            //树控件
            String[] colsInfo = item.getDictText().split(CgformUtil.SQL_COMMA);
            List<DictModel> ls  = sysBaseAPI.queryTableDictItemsByCode(item.getDictTable(), colsInfo[2], colsInfo[0]);
            dictOptions.put(dbFieldName,ls);
            column.setCustomRender(dbFieldName);
        }

        if(CgformUtil.CAT_TREE.equals(view)) {
            //分类字典树控件
            String dictText = item.getDictText();
            if(oConvertUtils.isEmpty(dictText)){
                //只存了id 需要在前端翻译
                String filterSql = CgformUtil.getSysCatgoryCondition(item.getDictField());
                List<DictModel> ls  = sysBaseAPI.queryFilterTableDictInfo(CgformUtil.CATEGORY_TABLE_NAME, CgformUtil.CATEGORY_TEXT_NAME, CgformUtil.CATEGORY_ID_NAME,filterSql);
                dictOptions.put(dbFieldName,ls);
                column.setCustomRender(dbFieldName);
            }else{
                //否则直接显示 该text
                column.setCustomRender( "_replace_text_"+dictText);
            }
        }

        //update-begin-author:taoyan date:20210609 for:【online】用户部门组件 现在有默认的存储/显示字段 能否支持通过配置 存储、显示哪个字段
        //部门选择也走字典加载
        if("sel_depart".equals(view)) {
            String[] temp = getStoreAndTextField(item.getFieldExtendJson());
            String storeField = temp[0].length()>0?temp[0]: CgformUtil.DEP_ID_NAME;
            String textField = temp[1].length()>0?temp[1]: CgformUtil.DEP_TEXT_NAME;
            List<DictModel> ls = sysBaseAPI.queryTableDictItemsByCode(CgformUtil.DEP_TABLE_NAME, textField, storeField);
            dictOptions.put(dbFieldName,ls);
            column.setCustomRender(dbFieldName);
        }
        //用户选择也走字典加载 若用户选择器 选择值改为username显示值为realname 则需要放开以下代码
        if("sel_user".equals(item.getFieldShowType())) {
            String[] temp = getStoreAndTextField(item.getFieldExtendJson());
            String storeField = temp[0].length()>0?temp[0]: CgformUtil.USER_LOGIN_NAME;
            String textField = temp[1].length()>0?temp[1]: CgformUtil.USER_REAL_NAME;
            List<DictModel> ls = sysBaseAPI.queryTableDictItemsByCode(CgformUtil.USER_TABLE_NAME, textField, storeField);
            dictOptions.put(dbFieldName,ls);
            column.setCustomRender(dbFieldName);
        }
        //update-end-author:taoyan date:20210609 for:【online】用户部门组件 现在有默认的存储/显示字段 能否支持通过配置 存储、显示哪个字段

        //判断文件
        if(view.indexOf(OnlFormShowType.file)>=0) {
            column.setScopedSlots(new ScopedSlots(OnlSlotRender.file));
        }else if(view.indexOf(OnlFormShowType.img)>=0) {
            column.setScopedSlots(new ScopedSlots(OnlSlotRender.img));
        }else if(view.indexOf(OnlFormShowType.editor)>=0) {
            column.setScopedSlots(new ScopedSlots(OnlSlotRender.html));
        }else if(view.equals(OnlFormShowType.date)) {
            column.setScopedSlots(new ScopedSlots(OnlSlotRender.date));
        }else if(view.equals(OnlFormShowType.pca)){
            column.setScopedSlots(new ScopedSlots(OnlSlotRender.pca));
        }
        // 判断是否填写了 href
        if (StringUtils.isNotBlank(item.getFieldHref())) {
            String slotName = OnlSlotRender.hrefPre + dbFieldName;

            column.setHrefSlotName(slotName);
            fieldHrefSlots.add(new HrefSlots(slotName,item.getFieldHref()));
        }
        //支持排序
        if("1".equals(item.getSortFlag())) {
            column.setSorter(true);
        }
        //update-begin-author:taoyan date:20201204 for:通过扩展参数设置列的最大长度
        String fieldExtendJson = item.getFieldExtendJson();
        if(StringUtil.isNotEmpty(fieldExtendJson) && fieldExtendJson.indexOf(ExtendJsonKey.SHOW_LEN)>0){
            JSONObject extJson = JSON.parseObject(fieldExtendJson);
            if(extJson!=null && extJson.get(ExtendJsonKey.SHOW_LEN)!=null){
                column.setShowLength(oConvertUtils.getInt(extJson.get(ExtendJsonKey.SHOW_LEN)));
            }
        }
        //update-end-author:taoyan date:20201204 for:通过扩展参数设置列的最大长度
        return column;
    }

    /**
     * 获取主表下所有子表的列配置
     * @param head
     * @param dictOptions
     * @param fieldHrefSlots
     * @param fieldRecord
     * @return
     */
    private List<OnlColumn> handleSubTableColumns(OnlCgformHead head, Map<String, List<DictModel>> dictOptions, List<HrefSlots> fieldHrefSlots, Map<String, Integer> fieldRecord){
        int tableType = head.getTableType();
        List<OnlColumn> ls = new ArrayList<>();
        if(tableType==2){
            String subTableString = head.getSubTableStr();
            if(subTableString!=null && !"".equals(subTableString)){
                String[] arr = subTableString.split(",");
                for(String tableName: arr){
                    LambdaQueryWrapper<OnlCgformHead> query = new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, tableName);
                    OnlCgformHead sub = onlCgformHeadService.getOne(query);
                    if(sub!=null){
                        //子表的未授权的隐藏字段
                        List<String> hideColumns = onlAuthPageService.queryHideCode(sub.getId(), true);
                        List<OnlCgformField> fieldList = getListColumns(sub.getId());
                        for(OnlCgformField item : fieldList){
                            //排除列 不显示且不查询的 下述逻辑可能处理查询的数据字典
                            if(CgformUtil.SHOW_LIST_YES!=item.getIsShowList() && CgformUtil.SHOW_LIST_YES!=item.getIsQuery()){
                                continue;
                            }
                            String dbFieldName = item.getDbFieldName();
                            //JTC-416 联合查询下列表需要限制子表字段，排除未授权的列字段
                            if(hideColumns.contains(dbFieldName)) {
                                continue;
                            }
                            //id 不显示
                            if(CgformUtil.COLUMN_ID.equals(dbFieldName)) {
                                continue;
                            }
                            Integer fieldNum = fieldRecord.get(dbFieldName);
                            if(fieldNum==null){
                                fieldRecord.put(dbFieldName, 1);
                            }else{
                                fieldRecord.put(dbFieldName, fieldNum+1);
                            }
                            OnlColumn column = getOnlColumnByField(item, dictOptions, fieldHrefSlots);
                            // 只有需要显示的列才往 集合中添加
                            if(CgformUtil.SHOW_LIST_YES==item.getIsShowList()){
                                column.setTableName(sub.getTableName());
                                ls.add(column);
                            }
                        }
                    }

                }

            }
        }
        return ls;
    }

}
